<template>
	<view class="page-container">
		<view class="head-container">
			<sys-notice></sys-notice>
			<uv-toast ref="toast"></uv-toast>
			<view class="textarea-container">
				<uv-input v-model="userInput" placeholder="请粘贴视频或图集作品链接,不用去除多余文字" border="surround" clearable
					:maxlength="280" @clear="clearInput"></uv-input>
			</view>
			<view class="btn-container">
				<uv-button class="btn-box" type="info" :plain="true" :hairline="true" text="粘贴"
					@click="setClipboard"></uv-button>
				<uv-button class="btn-box" type="primary" :hairline="true" text="去水印"
					@click="getNoWaterMarkVideo"></uv-button>
			</view>
			<view class="result-container" v-if="bodyShow">
				<view class="">
					<uv-subsection :list="list" :current="current" @change="change" activeColor="#2979ff" mode="button"
						bgColor="#f5f5f5" inactiveColor="#000000"></uv-subsection>
				</view>
				<view class="video-box">
					<uni-card class="card-box" margin="0px" padding="5px" spacing="0px" v-if="list[current]==='视频'">

						<view class="media-container">
							<video class="video-class" :src="video.url" :header="header" :autoplay="true"
								:custom-cache="false" :poster="video.cover"></video>
						</view>
						<view class="progress-box">
							<uv-line-progress v-if="progress.show" :percentage="progress.percentage"
								activeColor="#007aff"></uv-line-progress>
						</view>
						<view slot="actions" class="card-actions">
							<view class="card-actions-item">
								<uv-button type="primary" :plain="true" :hairline="true" icon="file-text-fill"
									text="复制链接" @click="copyVideoUrl" iconColor="#007aff"></uv-button>
							</view>
							<view class="card-actions-item">
								<uni-pagination :total="paging.total" prevText="<" nextText=">"
									:pageSize="paging.pageSize" :current="paging.pageNum"
									@change="changePage"></uni-pagination>
							</view>
							<view class="card-actions-item">
								<uv-button type="primary" :hairline="true" icon="download" text="下载视频"
									@click="downlaodSetting(()=>downloadVideo())" iconColor="#fff"></uv-button>
							</view>
						</view>
					</uni-card>
					<uni-card class="card-box" :isFull="true" margin="0px" padding="5px" spacing="0px"
						v-if="list[current]==='图片'">
						<view class="media-container">
							<uv-swiper class="video-class" height="225" :list="videoInfo.posterList"
								@change="changeImage" :current="imageVo.current" :autoplay="false" imgMode="aspectFit">
								<template v-slot:indicator>
									<view class="indicator-num">
										<text class="indicator-num__text">{{ imageVo.index }}/{{ imageVo.total }}</text>
									</view>
								</template>
							</uv-swiper>
						</view>
						<view class="">
							<progress-bar ref="progress-bar"></progress-bar>
						</view>
						<view slot="actions" class="card-actions">
							<view class="card-actions-item">
								<uv-button type="primary" :plain="true" :hairline="true" icon="file-text-fill"
									text="复制链接" @click="copyImageUrl" iconColor="#007aff"></uv-button>
							</view>
							<view class="card-actions-item" @click="actionsClick('copy')">

							</view>
							<view class="card-actions-item">
								<uv-button type="primary" :hairline="true" icon="download" :text="`下载图${imageVo.index}`"
									@click="downloadIMG(1)" iconColor="#fff"></uv-button>
							</view>
							<view class="card-actions-item">
								<uv-button type="primary" :hairline="true" icon="download" text="下载全部"
									@click="downloadIMG(2)" iconColor="#fff"></uv-button>
							</view>
						</view>
					</uni-card>
					<uni-card class="card-box" :isFull="true" margin="0px" padding="5px" spacing="0px"
						v-if="list[current]==='文案'">
						<view class="media-container">
							<uv-parse :content="videoInfo.videoTitle" :selectable="true"></uv-parse>
						</view>
						<view slot="actions" class="card-actions">
							<view class="card-actions-item">
								<uv-button type="primary" :plain="true" :hairline="true" icon="file-text-fill"
									text="复制文案" @click="copyVideoTitle" iconColor="#007aff"></uv-button>
							</view>
						</view>
					</uni-card>
				</view>
			</view>
		</view>

		<view class="tail-container">
			<view class="normal-question">
				<view class="recommend-friend">
					<uv-button type="default" icon="share-fill" openType="share" color="#ff1905" iconColor="#ff1905"
						:plain="true" :hairline="true" text="推荐好友"></uv-button>
				</view>
			</view>
			<view class="normal-question">
				<view class="btn-box">
					<uv-button type="default" icon="info-circle" color="#542525" iconColor="#542525" :plain="true"
						:hairline="true" text="常见问题" @click="normalQuestionHandle"></uv-button>
					<uv-button type="default" icon="chat" openType="contact" color="#50a1f1" iconColor="#50a1f1"
						:plain="true" :hairline="true" text="联系客服"></uv-button>
				</view>
			</view>
			<view class="normal-question">
				<tail-notice></tail-notice>
			</view>
		</view>
	</view>

</template>

<script>
	import {
		transNoWaterMark
	} from "@/common/api.js"
	import {
		download_video_url
	} from "@/common/backend_url.js"
	export default {
		data() {
			return {
				userInput: "",
				extraIcon: {
					color: '#4cd964',
					size: '22',
					type: 'gear-filled'
				},
				list: ['视频', '图片', '文案'],
				videoInfo: {},
				video: {
					url: "",
					cover: ""
				},
				paging: {
					total: 1,
					pageNum: 1,
					pageSize: 1,
				},
				header: {
					"Referer": ""
				},
				imageVo: {
					index: 1,
					url: "",
					total: 1,
					current: 0
				},
				bodyShow: false,
				progress: {
					percentage: 0,
					show: false
				},
				video_download: [],
				current: 0,
			}
		},

		onShow() {
			//this.header.Referer = this.videoInfo.video_url;
		},
		onLoad() {

		},
		methods: {
			click(item) {
				console.log('item', item);
			},
			setClipboard() {
				uni.getClipboardData({
					success: (res) => {
						this.userInput = res.data
					}
				})
			},
			change(index) {
				this.current = index;
				if (this.list[index] === "视频") {
					this.pageNum = 1;
				}
				if (this.list[index] === "图片") {
					this.imageVo.url = this.videoInfo.posterList[0]
					this.imageVo.total = this.videoInfo.posterList.length
				}
			},
			actionsClick(param) {
				console.log(param)
			},
			getNoWaterMarkVideo() {
				//关闭上次搜索结果面板
				this.bodyShow = false
				//清空上次的视频和图片数据
				this.videoInfo = {};

				//清空下载缓存
				this.video_download = []
				const reg = new RegExp("((http|https)://[^\\s/$.?#].[^\\s]*)", "g")
				const matchs = this.userInput.match(reg)
				if (!matchs) {
					this.userInput = "";
					this.$refs.toast.show({
						type: "default",
						message: "请输入带视频的网页地址",
						duration: 2000
					});
					return;
				} else {
					this.userInput = matchs[0]
				}
				const data = {
					userInput: this.userInput
				}
				uni.showLoading({
					title: "请稍候...",
					mask: true
				})
				transNoWaterMark(data).then(res => {
					if (res.data) {
						this.videoInfo = res.data;
						this.bodyShow = true
						this.initVideoInfo()
						uni.hideLoading()
					} else {
						uni.showToast({
							title: res.msg,
							duration: 2000,
							icon: "error",
							mask: true
						})
					}

				}).catch(error => {
					uni.showToast({
						title: "去水印失败!",
						duration: 2000,
						icon: "error",
						mask: true
					})
					uni.hideLoading()
					console.log(error)
				})
			},
			initVideoInfo() {
				if (this.videoInfo?.videoList) {
					this.list = ['视频', '图片', '文案']
					this.video.url = this.videoInfo.videoList[0]
					this.video.cover = this.videoInfo.posterList[0]
					this.paging.total = this.videoInfo.videoList.length
					this.paging.pageNum = 1;
				} else {
					this.list = ['图片', '文案']
				}
				this.current = 0;
				this.imageVo.current = 0
				this.imageVo.index = 1
				this.imageVo.url = this.videoInfo.posterList[0]
				this.imageVo.total = this.videoInfo.posterList.length
			},
			changePage(e) {
				const {
					current
				} = e
				this.paging.pageNum = current
				this.video.url = this.videoInfo.videoList[current - 1]
				this.video.cover = this.videoInfo.posterList[current - 1]

			},
			changeImage(e) {
				const {
					current
				} = e
				this.imageVo.current = current
				this.imageVo.index = current + 1
				this.imageVo.url = this.videoInfo.posterList[current]
			},
			clearInput() {
				this.userInput = "";
				this.bodyShow = false
			},
			copyVideoUrl() {
				uni.setClipboardData({
					data: this.video.url
				})
			},
			copyImageUrl() {
				uni.setClipboardData({
					data: this.imageVo.url
				})
			},
			copyVideoTitle() {
				uni.setClipboardData({
					data: this.videoInfo.videoTitle
				})
			},
			downloadIMG(value) {
				//下载当前图片
				if (value === 1) {
					this.downlaodSetting(() => this.downloadImage(this.imageVo.url, this.imageVo.index, value));
				}
				//下载所有图片
				if (value === 2) {
					this.downlaodSetting(() => this.downloadImages(value));
				}
			},
			async downloadImages(value) {
				const videoList = this.videoInfo.posterList;
				console.log("开始下载")
				for (let i = 0; i < videoList.length; i++) {
					await this.downloadImage(videoList[i], i + 1, value)
				}
				console.log("下载完毕")
			},
			async downloadImage(url, index, type) {
				const tempFilePath = await this.downlaodFile(url, index, type);
				await uni.saveImageToPhotosAlbum({
					filePath: tempFilePath
				})
				console.log("tempFilePath:", tempFilePath)

			},
			downlaodFile(url, index, type) {
				return new Promise((resolve, reject) => {
					const downloadTask = uni.downloadFile({
						url: url,
						success: (res) => {
							if (res.statusCode === 200) {
								resolve(res.tempFilePath)
							} else {
								reject(new Error('下载失败'))
							}
						},
						fail: (err) => {
							reject(new Error('下载失败'))
						}
					})
					downloadTask.onProgressUpdate((res) => {
						if (type === 1) {
							this.$refs["progress-bar"].startDownload(index, res.progress, 1);
						}
						if (type === 2) {
							this.$refs["progress-bar"].startDownload(index, res.progress, this.videoInfo
								.posterList.length);
						}
					});
				})

			},
			downloadVideo() {
				//从缓存中查找已经下载的资源，避免再次下载
				const obj = this.video_download.find(item => item.index === (this.paging.pageNum - 1));
				if (obj) {
					uni.saveVideoToPhotosAlbum({
						filePath: obj.path,
						success: () => {
							uni.showToast({
								title: "保存视频成功",
								duration: 2000
							})
						}
					})
					return;
				}
				this.progress.show = true
				const downloadTask = uni.downloadFile({
					url: this.video.url,
					success: (res) => {
						console.log(res)
						if (res.statusCode != 200) {
							//如果前端下载不了,尝试经由服务器下载
							this.downloadByServer()
						} else {
							console.log(res.tempFilePath)
							const cache = {
								index: this.paging.pageNum - 1,
								path: res.tempFilePath
							}
							this.video_download.push(cache);
							uni.saveVideoToPhotosAlbum({
								filePath: res.tempFilePath,
								success: () => {
									uni.showToast({
										title: "保存视频成功",
										duration: 2000
									})
								}
							})
						}
					},
					fail: (error) => {
						//如果下载失败，尝试使用服务器进行下载
						this.downloadByServer()
					}
				})
				downloadTask.onProgressUpdate((res) => {
					this.progress.percentage = res.progress;
					if (res.progress === 100) {
						setTimeout(() => {
							this.progress.show = false;
						}, 2000)
					}
				});
			},
			downloadByServer() {
				uni.showLoading({
					title: "下载中,请稍候...",
					mask: true
				})
				const download = uni.downloadFile({
					url: download_video_url + "?url=" + encodeURIComponent(this.video.url),
					success: (res) => {
						const cache = {
							index: this.paging.pageNum - 1,
							path: res.tempFilePath
						}
						this.video_download.push(cache);
						uni.saveVideoToPhotosAlbum({
							filePath: res.tempFilePath,
							success: () => {
								uni.hideLoading()
								uni.showToast({
									title: "保存视频成功",
									duration: 2000
								})
							}
						})
					},
					fail: () => {
						uni.hideLoading()
						uni.showToast({
							title: "保存视频失败",
							icon: "error",
							duration: 2000
						})
						setTimeout(() => {
							this.progress.show = false;
						}, 2000)
					}
				})
				download.onProgressUpdate((res) => {
					this.progress.percentage = res.progress;
					if (res.progress === 100) {
						setTimeout(() => {
							this.progress.show = false;
						}, 2000)
					}
				});
			},
			downlaodSetting(fn) {
				uni.getSetting({
					success: (res) => {
						if (!res.authSetting['scope.writePhotosAlbum']) {
							uni.authorize({
								scope: 'scope.writePhotosAlbum',
								success: () => {
									fn();
								},
								fail: (err) => {
									console.log('授权失败:', err)
								}
							})
						} else if (!res.authSetting['scope.writePhotosAlbum']) {
							wx.openSetting({
								success: (res) => {
									if (res.authSetting['scope.writePhotosAlbum']) {
										fn();
									}
								}
							})
						} else {
							fn();
						}
					}
				})
			},
			normalQuestionHandle() {
				uni.navigateTo({
					url: "/pages/question/question"
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.page-container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		justify-content: space-between;

		.head-container {

			.btn-container {
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				margin: 5px 10px;
				height: 30px;
				justify-items: center;
			}

			.textarea-container {
				margin: 10px 5px 10px 5px;
			}

			.result-container {
				margin: 10px 5px;
				border: 1px solid #c7c7c7;

				.video-box {
					display: flex;
					align-items: center;
					justify-content: center;
					width: 100%;

					.card-box {
						width: 100%;

						.media-container {
							width: 100%;

							.video-class {
								width: 100%;
								margin: 0px auto;
							}
						}

						.card-actions {
							display: flex;
							flex-direction: row;
							justify-content: space-around;
							align-items: center;
							height: 45px;
							border-top: 1px #eee solid;
						}

						.card-actions-item {
							display: flex;
							flex-direction: row;
							align-items: center;
						}

						.card-actions-item-text {
							font-size: 12px;
							color: #666;
							margin-left: 5px;
						}
					}

				}

			}

		}

		.tail-container {
			.normal-question {
				margin: 10px 10px;

				.btn-box {
					display: flex;
					flex-direction: row;
					justify-content: space-around;
					align-items: center;
				}
			}
		}


	}
</style>